package com.gehj.androidlibs;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.View;

import com.gehj.androidlibs.databinding.ActivityTabLayoutBinding;
import com.gehj.androidlibs.fragments.BlankFragment;
import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
//IMPORTANT: 很奇怪BlankFragment中的textview会引起内存泄漏；
public class TabLayoutActivity extends AppCompatActivity {
    ActivityTabLayoutBinding binding ;
    public static final String[] tabTitles =
            new String[]{"tab1","tab2","tab3","tab4",
                    "tab5","tab6","tab7","tab8","tab9"};
    private List<BlankFragment> mFragments = new ArrayList<BlankFragment>();
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityTabLayoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
    }

    private void initView() {
       mTabLayout =  binding.tabLayout;
       mViewPager =   binding.viewpager2;

        for(int i = 0; i < tabTitles.length; i++) {
            mFragments.add(BlankFragment.newInstance(tabTitles[i],null));
        }

        //为ViewPager设置FragmentPagerAdapter
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @NotNull
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }


            @Nullable
            @org.jetbrains.annotations.Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return tabTitles[position];
            }
        });

        //TabLaout和ViewPager进行关联
        mTabLayout.setupWithViewPager(mViewPager);
        //防止tab太多，都拥挤在一起
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }
}